import sys
import time
import threading
from PyQt6.QtCore import pyqtSignal, QObject, QEventLoop
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QTextEdit
from selenium import webdriver
from PyQt6.QtGui import QTextCursor
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QMessageBox


# 定义一个信号类，用于在线程和界面交互中传递暂停、恢复等信号
class ThreadSignal(QObject):
    is_paused = False
    paused = pyqtSignal()
    resumed = pyqtSignal()


# 工作线程类，执行具体的循环操作任务
class WorkerThread(threading.Thread):
    def __init__(self, signal, text_edit):
        super().__init__()
        self.signal = signal
        self.text_edit = text_edit
        self.is_running = True

    def run(self):
        loop = QEventLoop()
        while self.is_running:
            if not self.signal.is_paused:
                current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
                self.text_edit.moveCursor(QTextCursor.MoveOperation.End)
                self.text_edit.insertPlainText(current_time + '\n')
                self.text_edit.ensureCursorVisible()
                time.sleep(1)
            else:
                # 使用QEventLoop来等待恢复信号，而不是直接调用wait方法
                self.signal.resumed.connect(loop.quit)
                loop.exec()


class MyWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.thread_signal = ThreadSignal()
        self.thread = None
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout()

        # 创建启动按钮并连接点击事件处理函数
        start_button = QPushButton('启动')
        start_button.clicked.connect(self.start_clicked)
        layout.addWidget(start_button)

        # 创建暂停按钮并连接点击事件处理函数
        pause_button = QPushButton('暂停')
        pause_button.clicked.connect(self.pause_clicked)
        layout.addWidget(pause_button)

        # 创建文本框
        self.text_edit = QTextEdit()
        self.text_edit.setFixedHeight(30)  # 设置文本框高度为一行
        layout.addWidget(self.text_edit)

        self.setLayout(layout)

        self.setWindowTitle('功能示例窗口')
        self.show()

    def start_clicked(self):
        if self.thread is None:
            # 使用Selenium打开百度网页
            self.driver = webdriver.Chrome()
            self.driver.get("https://www.baidu.com/")

            # 弹出对话框提示用户点击准备好按钮
            msg_box = QMessageBox()
            msg_box.setText("请点击准备好按钮继续")
            msg_box.setStandardButtons(QMessageBox.StandardButton.Ok)
            msg_box.exec()

            # 启动线程
            self.thread = WorkerThread(self.thread_signal, self.text_edit)
            self.thread.start()
        elif self.thread_signal.is_paused:
            # 如果线程已暂停，发送恢复信号
            self.thread_signal.is_paused = False
            self.thread_signal.resumed.emit()

    def pause_clicked(self):
        if self.thread is not None:
            # 设置暂停信号为True，并发送暂停信号
            self.thread_signal.is_paused = True
            self.thread_signal.paused.emit()

    def closeEvent(self, event):
        # 关闭窗口时，停止线程并关闭浏览器
        if self.thread is not None:
            self.thread.is_running = False
            self.thread.join()
        if hasattr(self, 'driver'):
            self.driver.quit()
        event.accept()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    widget = MyWidget()
    sys.exit(app.exec())